<?php

namespace app\system\controller\business;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Arr;
use think\facade\Config;
use think\facade\Db;


class Information extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name', 'describe'];

    protected string $goodsField = 'g.*, h.hscode';


    public function initialize(): void {
        parent::initialize();
    }


    public function getHscode(){
        $param = $this->request->param();
        $result = db::name('hscode')->order('id asc')->select();
        $this->success('', [
            'list' => $result
        ]);
    }


    public function getHscodeSku(){
        $param = $this->request->param();
        $result = db::name('hscode_sku')->where(['hscode_id' => $param['id']])->order('id asc')->select()->toArray();

        foreach($result as &$val){
            $val['attach_' . $val['id']] = '';
        }

        $this->success('', $result);
    }


    public function saveFile(){
        $params = $this->request->param();

        if(empty($params['file_url'])) $this->error(__('文件信息获取失败'));

        $order = db::name('customer_order')->where(['id' => $params['order_id']])->find();

        $insert = [];
        foreach($params['file_url'] as $val){
            $where = [
                'url' => html_entity_decode($val)
            ];
            $file_result = db::name('attachment')->where($where)->find();

            $insert[] = [
                'order_id' => $params['order_id'],
                'out_trade_no' => $order['out_trade_no'],
                'file_link' => $file_result['url'],
                'file_name' => $file_result['name'],
                'type' => $params['type']
            ];
        }
        db::name('order_file')->insertAll($insert);
        $this->success();
    }

    /**
     * 生成发票号
     */
    public function generatePiNum(){
        $params = $this->request->param();
        $sign_date = date("ymd", strtotime($params['date']));
        $sign = db::name('customer_order_sign')->where(['sign_date' => $params['date']])->select()->toArray();
        if($sign){ // 该日期下非初次生成发票号
            $num = count($sign) + 1;
            $num = $num > 9 ? $num : '0' . $num;
            $pi_num = 'WHYNOT ' . $sign_date . $num;
        }else{
            $pi_num = 'WHYNOT ' . $sign_date . '01';
        }
        $_sign = db::name('customer_order_sign')->where(['order_id' => $params['order_id']])->find();
        if($_sign){
            $update = [
                'sign_date' => $params['date'],
                'pi_num' => $pi_num,
                'update_time' => $this->timestamp
            ];
            db::name('customer_order_sign')->where(['id' => $_sign['id']])->update($update);
        }else{
            $insert = [
                'order_id' => $params['order_id'],
                'sign_date' => $params['date'],
                'pi_num' => $pi_num,
                'create_time' => $this->timestamp
            ];
            db::name('customer_order_sign')->insert($insert);
        }
        $this->success('', $pi_num);
    }


    /**
     * 保存基础表单的信息
     */
    public function saveInformation() {
         $param = $this->request->param();
//         print_r($param);die;
        if(!empty($param['customer_contact']) && strlen($param['customer_contact']) > 20) $this->error(__('买方联系电话长度超出限制'));
         $where = [
             'order_id' => $param['order_id']
         ];
         $information = db::name('customer_order_information')->where($where)->find();
         if($information){
             $param['update_time'] = $this->timestamp;
             $result = db::name('customer_order_information')->where(['id' => $information['id']])->update($param);
         }else{
             $param['create_time'] = $this->timestamp;
             $result = db::name('customer_order_information')->insert($param);
         }
         if($result){
             $this->success();
         }else{
             $this->error();
         }
    }

    public function getGoodsHscode(){
        $param = $this->request->param();
        $goods = db::name('customer_order_goods')->where(['id' => $param['id']])->find();
        if(empty($goods['hscode_id'])){
            $hscode_sku = [];
        }else{
            $hscode_sku = db::name('hscode_sku')->where(['hscode_id' => $goods['hscode_id']])->select();
            if(!$hscode_sku){
                $hscode_sku = [];
            }
        }
//        $goods['deal_unit_amount'] = empty($goods['deal_unit_amount']) ? null : $goods['deal_unit_amount'] / 100;
//        $goods['deal_amount'] = empty($goods['deal_amount']) ? null : $goods['deal_amount'] / 100;
        $this->success('', [
            'hscode_sku' => $hscode_sku,
            'goods_sku' => empty($goods['hscode_sku']) ? [] : json_decode($goods['hscode_sku'], true)
        ]);
    }


    public function saveInformationGoods() {
        $param = $this->request->param();
//        print_r($param);die;
        $insert = $param['goodsForm'];
        $insert['hscode_sku'] = empty($param['hscodeForm']) ? null : json_encode($param['hscodeForm']);
        $result = db::name('customer_order_goods')->insert($insert);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
        print_r($param);die;
    }
    public function updateInformationGoods(){
        $param = $this->request->param();

        $update = $param['goodsForm'];
        $update['hscode_sku'] = empty($param['hscodeForm']) ? null : json_encode($param['hscodeForm']);
        $update['update_time'] = $this->timestamp;

        $update['deal_unit_amount'] = empty($update['deal_unit_amount']) ? null : $update['deal_unit_amount'] * 100;
        $update['deal_amount'] = empty($update['deal_amount']) ? null : $update['deal_amount'] * 100;

//        print_r($update);die;
        $update['gross_weight'] = $update['gross_weight'] == '' ? null : $update['gross_weight'];
        $update['net_weight'] = $update['net_weight'] == '' ? null : $update['net_weight'];
        $result = db::name('customer_order_goods')->where(['id' => $param['goodsForm']['id']])->update($update);


        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    public function getInformationGoods(){
        $params = $this->request->param();
        $list = db::name('customer_order_goods')->alias('g')->field($this->goodsField)
            ->leftJoin('hscode h', 'h.id=g.hscode_id')
            ->where(['g.order_id' => $params['order_id']])
            ->order('g.id asc')
            ->select();
        $this->success('', [
            'goods' => $list
        ]);
    }

    public function delGoods(){
        $params = $this->request->param();
        $goods = db::name('customer_order_goods')->where(['id' => $params['id']])->find();
        db::name('customer_order_goods')->where(['id' => $params['id']])->delete();
        $list = db::name('customer_order_goods')->alias('g')->field($this->goodsField)
            ->leftJoin('hscode h', 'h.id=g.hscode_id')
            ->where(['g.order_id' => $goods['order_id']])
            ->order('g.id asc')
            ->select();
        $this->success('', [
            'goods' => $list
        ]);
    }

    public function delFile(){
        $params = $this->request->param();
        db::name('order_file')->where(['id' => $params['file_id']])->delete();
        $this->success();
    }



    /**
     * 获取资料管理的默认信息
     */

    public function getFile(){
        $params = $this->request->param();
        $order = db::name('customer_order')->where(['id' => $params['order_id']])->find();
        $order_file = db::name('order_file')->where(['out_trade_no' => $order['out_trade_no']])->select();
        $file = [];
//        print_r($order_file);die;
        foreach ($order_file as $item) {
            $key = $item['type'];
            if (!isset($file[$key])) {
                $file[$key] = [];
            }
            $item['file_name'] = html_entity_decode($item['file_name']);
            if($order['id'] == $item['order_id']){
                $file[$key][] = $item;
            }

        }
        $this->success('', [
            'file' => $file
        ]);



    }




}